package edu.xjdx.os.controller;

import edu.xjdx.os.domain.Discount;
import edu.xjdx.os.service.DiscountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/discount")
public class DiscountController {
    @Autowired
    DiscountService service;

    @RequestMapping("/list")
    public String listDiscount(Model model){
        List<Discount>discounts = service.listAll();
        model.addAttribute("discount",discounts);
        return "back/discount_list";
    }

    @PostMapping("/delete")
    @ResponseBody
    public Object listDelete(String id){
        Map<String,Object> map=new HashMap<>();
        if(service.remove(id)){
            map.put("ok",true);
        }else{
            map.put("ok",false);
        }

        return map;
    }

    @RequestMapping(value = "/modify",method = RequestMethod.POST)
    public String update(Discount discount){
        if(service.update(discount)==true){
            return "redirect:/discount/list";
        }else {
            return "redirect:/discount/list";
        }
    }

    @PostMapping("/add")
    public String addCustomer(Discount discount){
        if(service.addDiscount(discount)==0){
            return "redirect:/discount/list";
        }else if(service.addDiscount(discount)==1){
            return "back/discount_add";
        }
        return "back/discount_add";
    }

    @GetMapping("/add")
    public String addCustomer(){
        return "back/discount_add";
    }
}
